package com.example.demo.concurrent.unsafe;

import com.example.demo.concurrent.AtomicTest.MyUnSafe.UnSafeAccessor;
import sun.misc.Unsafe;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-09-15
 * Time: 13:02
 */
public class AtomicData {
    // 要自增的数据
    private volatile int data;
    // UnSafe对象
    private static final Unsafe UNSAFE;
    // 得到数据的偏移量
    private static final long DATA_OFFSET;
    static {
        UNSAFE = UnSafeAccessor.getUnsafe();
        try {
            DATA_OFFSET = UNSAFE.objectFieldOffset(AtomicData.class.getDeclaredField("data"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public AtomicData(int data) {
        this.data = data;
    }

    public void decrease(int next) {
        // 获取共享变量的旧值
        int oldValue;
        while(true) {
            oldValue = data;
            if(UNSAFE.compareAndSwapInt(this,DATA_OFFSET,oldValue,next)) {
                return;
            }
        }
    }
    public int getData() {
        return data;
    }
}